/*
 * @Author: your name
 * @Date: 2021-02-01 15:23:40
 * @LastEditTime: 2021-02-03 19:58:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \wwwd:\凯哥购物项目\pages\cart\index.js
 */
// pages/cart/index.js
import { showModal, showToast } from "../../utils/asyncWx";
import { getCartInfo,setCartInfo,deleteCartOne} from "../../api/cart.js";
import { getAddressInfo} from "../../api/address.js";
import { createOrderOne} from "../../api/order.js";


Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: [],
        cart: [],
        allChecked: false,
        totalPrice: 0,
        totalNum: 0,
        chooseAddress: {},
        userid:"",
        createOrder:[]
    },

    onShow: async function() {
        let userid= wx.getStorageSync('userid')
        if(!userid){
            wx.switchTab({
                url: '/pages/user/index',
            })
            await showToast({ title: "请先登录" });
        }else{
            await this.getCart()
            this.handleChooseAddress()
            this.setCart();
        }
    },

    async handleChooseAddress() {
        let userid= wx.getStorageSync('userid')
        const address = await getAddressInfo(userid);
     var chooseAddress = address.find(v=>v.isChecked==true)
      this.setData({
        chooseAddress
      })
    },


    async getCart(){
        const userid = wx.getStorageSync('userid')
        const result =await getCartInfo(userid)
        console.log(result);
    this.setData({
        cart:result
    })
    },


    //复选框触发事件
   async handleItemChange(e) {
    let userid= wx.getStorageSync('userid')
        const id = e.currentTarget.dataset.id;
        let { cart } = this.data;
        console.log(userid);
        let index = cart.findIndex(v => v.id === id);
        cart[index].is_check = !cart[index].is_check;
        const result2 = await setCartInfo(userid,id,'check')
      if(result2){
        this.getCart()
        this.setCart();
      }
    },

    //重新计算
    setCart() {
        let cart = this.data.cart
        let allChecked = this.data.allChecked;
        let totalPrice = 0;
        let totalNum = 0;
        let checkNum = 0;
        console.log(cart);
        cart.forEach(v => {
            if (v.is_check) {
                checkNum++;
                totalPrice += v.number * v.goods_price;
                totalNum += v.number;
            } else {
            }
        })
        allChecked = (cart.length==checkNum) ? true : false;
        console.log(allChecked);
        this.setData({
            cart,
            allChecked,
            totalPrice,
            totalNum,
            createOrder:[]
        })
    },

    async handleItemAllCheck() {
        let { cart, allChecked } = this.data;
        let userid =wx.getStorageSync('userid')
        console.log(userid);
        allChecked = !allChecked;
        console.log(cart);
        cart.forEach(async v => {
            if(v.is_check != allChecked){
                const result2 = await setCartInfo(userid,v.id,'check')
                console.log(result2);
            }
            console.log(allChecked);
        });
       await this.getCart();
        this.setCart();
    },

    //商品加减
    async handleItemNumEdit(e) {
        const userid = wx.getStorageSync('userid')
        const { operation, id } = e.currentTarget.dataset;
        console.log(e.currentTarget.dataset);
        let { cart } = this.data;
        const index = cart.findIndex(v => v.id === id);
        console.log();
        if (cart[index].number === 1 && operation === "-") {
            const res = await showModal({ content: "是否删除？" });
            if (res.confirm) {
                const result2 = await deleteCartOne(userid,id);
              this.getCart()
              this.setCart()
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        } else {
            const result2 = await setCartInfo(userid,id,operation);
              console.log(index);
            cart[index].number = result2.number;
            this.setCart();
        }
    },

    async handlePay() {
         var createOrder=new Array();
        const { chooseAddress, totalNum } = this.data;
        console.log();
        if (!chooseAddress.username) {
            await showToast({ title: "您没选择收获地址" });
            return;
        } else if (totalNum === 0) {
            await showToast({ title: "您还没选择购物商品" });
            return;
        } else {
            function current() {
                var d = new Date(),
                    str = '';
                str += d.getFullYear() + '/'; //获取当前年份 
                str += d.getMonth() + 1 + '/'; //获取当前月份（0——11） 
                str += d.getDate() + ' ';
                str += d.getHours() + ':';
                str += d.getMinutes() + ':';
                str += d.getSeconds();
                return str;
            }
            var time = current();
            var cart = this.data.cart
            var userid =wx.getStorageSync('userid')
            let orderNum = 0
            cart.forEach(async v=>{
                const order = await createOrderOne(userid,v.goods_id,time,v.number,"0")
               createOrder.push(order)
               wx.setStorageSync('createOrder', createOrder)
              if(order){
                this.setData({
                    order
                })
                orderNum++;
             }
             if(orderNum)
             {
                await showToast({ title: "成功生成订单"+orderNum});
             }
            })
            wx.navigateTo({
                url: '/pages/pay/index',
            })
        }
    },
})